import json
import os
import logging

# 配置文件路径
USER_DATA_PATH = os.getenv("USER_DATA_PATH", "F:\\桌面\\Python基础准备\\user.json")


class User:
    def __init__(self, username, password, role):
        if role not in ['admin', 'user']:
            raise ValueError("无效的角色代码. 角色代码必须是 user (普通用户) 或 admin (管理员).")
        self.username = username
        self.password = password
        self.role = role

    @staticmethod
    def _load_user_data():
        try:
            with open(USER_DATA_PATH, 'r', encoding='utf-8') as file:
                data = json.load(file)
                if not data or not isinstance(data, list):
                    logging.error("用户数据为空或者不是一个列表，返回None")
                    return None
                return data
        except FileNotFoundError:
            logging.error(f"用户数据文件未找到，路径为: {USER_DATA_PATH}")
            return None
        except json.JSONDecodeError:
            logging.error(f"无效的JSON格式，路径为: {USER_DATA_PATH}")
            return

    @staticmethod
    def search_user(username):
        data = User._load_user_data()
        if data is None:
            return None
        for user_data in data:
            if user_data.get('username') == username:
                return True
        return False

    @staticmethod
    def search_user_by_id(id):
        data = User._load_user_data()
        if data is None:
            return None
        for user_data in data:
            if user_data.get('id') == id:
                return True
        return False

    @classmethod
    def login(cls, username, password):
        data = User._load_user_data()
        if data is None:
            return None

        for user_data in data:
            if user_data.get('username') == username and user_data.get('password') == password:
                return cls(username, user_data.get('username'), user_data.get('role'))

        logging.info(f"{username}用户登录失败")
        return None
